import {useState} from "react";
import {useImmer} from "use-immer";

const ChangeStateArray = ()=>{
    const [names,setNames] = useImmer(['张三','李四','王五'].map(item=>{
        return {name:item,isEdit:false}
    }))
    const [name,setName] = useState('')

    const addName = (e)=>{
        setName(e.target.value)
    }

    const pushName = ()=>{
        setName('')

        // 错误的不推荐
        // names.push({name,isEdit: false})

        // 正确写法
        // setNames(names.concat({name,isEdit: false}))
        // 在数组中间插入元素
        // setNames([
        //     // 0~2不包括2，包括0，slice区间是左闭右开的
        //     ...names.slice(0,2),
        //     {name,isEdit: false},
        //     ...names.slice(2)
        // ])
        // 使用useImmer来插入数据
        setNames(draft => {
            draft.splice(2,0,{name,isEdit: false})
        })
    }


    const lis = names.map((item,index)=>{
        const onBlur = ()=>{
            const nextNames = names.map((item)=>{
                return {...item,isEdit:false}
            })
            setNames(nextNames)
        }

        const onChange = (name,i1)=>{
            const nextNames = names.map((item,i2)=>{
                if(i1 === i2) return {...item,name}
                return item
            })
            setNames(nextNames)
        }

        const input = <input

            value={item.name}
            onBlur={()=>onBlur(index)}
            onChange={(e)=>onChange(e.target.value,index)}
            autoFocus={true}/>

        const onDoubleClick = (i1)=>{
            const nextNames = names.map((item,i2)=>{
                return {...item,isEdit:i1 === i2}
            })
            setNames(nextNames)
        }

        return (
            <li onDoubleClick={()=>onDoubleClick(index)} key={index}>
                {item.isEdit?input:item.name}
            </li>
        )
    })
    return (
        <>
            <input onChange={addName} value={name}/>
            <ul>
                {lis}
            </ul>
            <button onClick={pushName}>添加</button>
        </>
    )
}

export default ChangeStateArray